/**
 * 结伴页面
 * /pages/buddy/index
 * @author WeChat Mini Program Team
 * @since 2025-08-14
 */

const Router = require('../../utils/router')
const Storage = require('../../utils/storage')
const Logger = require('../../utils/logger')
const Track = require('../../utils/track')

// 引入相关服务
const { CommunityService, TeacherService, BuddyService, SwapService, UserService } = require('../../services/index')

Page({
  /**
   * 页面的初始数据
   */
  data: {
    title: '结伴',
    loading: false,
    // 列表数据
    dataList: [],
    hasMore: true,
    loadingMore: false,
    refreshing: false,
    page: 1,
    limit: 20,
    
    // 搜索
    searchKeyword: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    Logger.info('Page loaded: /pages/buddy/index', options)
    Track.trackPageView('/pages/buddy/index', options)
    
    // 加载列表数据
    this.loadData()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 页面显示时的逻辑
  },

  /**
   * 加载列表数据
   */
  async loadData(refresh = false) {
    if (this.data.loading) return
    
    try {
      this.setData({ 
        loading: refresh ? false : this.data.dataList.length === 0,
        refreshing: refresh,
        loadingMore: !refresh && this.data.page > 1
      })
      
      const params = {
        page: refresh ? 1 : this.data.page,
        limit: this.data.limit,
        keyword: this.data.searchKeyword
      }
      
      // TODO: 替换为实际的API调用
      // const response = await SomeService.getList(params)
      
      // 模拟数据
      const response = {
        success: true,
        data: {
          items: [
            {
              id: 1,
              title: '结伴晨跑',
              description: '每天清晨6点，社区公园集合，欢迎加入！',
              createTime: '2025-08-18 07:00'
            },
            {
              id: 2,
              title: '周末读书会',
              description: '一起读书交流，提升自我。',
              createTime: '2025-08-17 10:00'
            },
            {
              id: 3,
              title: '羽毛球搭子招募',
              description: '每周三晚，羽毛球馆不见不散。',
              createTime: '2025-08-16 19:00'
            }
          ],
          hasMore: false,
          total: 3
        }
      }
      
      if (response.success) {
        const newData = refresh 
          ? response.data.items 
          : [...this.data.dataList, ...response.data.items]
          
        this.setData({
          dataList: newData,
          hasMore: response.data.hasMore,
          page: refresh ? 2 : this.data.page + 1
        })
      }
    } catch (error) {
      Logger.error('Failed to load data', error)
      wx.showToast({ title: '加载失败', icon: 'error' })
    } finally {
      this.setData({
        loading: false,
        refreshing: false,
        loadingMore: false
      })
    }
  },

  /**
   * 列表项点击
   */
  onItemTap(e) {
    const item = e.currentTarget.dataset.item
    Track.trackClick('list_item', 'list_item', { id: item.id })
    
    // TODO: 跳转到详情页
    // Router.navigateTo('path/to/detail', { id: item.id })
  },

  /**
   * 搜索
   */
  onSearch(e) {
    const keyword = e.detail.value
    this.setData({ 
      searchKeyword: keyword,
      page: 1,
      dataList: []
    })
    this.loadData(true)
  },

  /**
   * 清除搜索
   */
  onSearchClear() {
    this.setData({ 
      searchKeyword: '',
      page: 1,
      dataList: []
    })
    this.loadData(true)
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.loadData(true)
  },

  /**
   * 上拉加载更多
   */
  onReachBottom() {
    if (this.data.hasMore && !this.data.loadingMore) {
      this.loadData()
    }
  },

  /**
   * 加载更多
   */
  onLoadMore() {
    this.onReachBottom()
  },

  /**
   * 重试
   */
  onRetry() {
    this.loadData(true)
  },
})